import * as THREE from '../../../build/three.module.min.js';
import { OrbitControls } from '../../../jsm/controls/OrbitControls.js';
import { GLTFLoader } from '../../../jsm/loaders/GLTFLoader.js';
import { GUI } from '../../../jsm/libs/lil-gui.module.min.js';

// 场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf6eedc);

// 相机
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(1.5, 4, 9);

// 渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 环境光
const al = new THREE.AmbientLight();
al.intensity = 5;
al.color = new THREE.Color().set(1, 1, 1);
scene.add(al);

// 辅助平面
const gridHelper = new THREE.GridHelper(100, 10);
scene.add(gridHelper);

// 渲染驱动
const render = () => {
  renderer.render(scene, camera);
};

// 模型加载
const loader = new GLTFLoader();
loader.setPath('/models/gltf/');
loader.load('my-person.glb', (gltf) => {
  console.log(gltf);
  scene.add(gltf.scene);

  render();

  // 调试器
  // 定位数据
  const pos = {
    x: 0,
    y: 0,
    z: 0
  }
  // 颜色数据
  const color = {
    color: '#ffffff'
  }

  const gui = new GUI();

  // 定位处理函数
  const handlePosChange = (target, prop, value) => {
    target.position[prop] = value
    render();
  }
  
  // 颜色处理函数
  const handleColorChange = (target, value) => {
    if (target.material.color.isColor) {
      target.material.color = new THREE.Color(value);
    }
    render();
  }

  // 遍历可操作模型
  for(let i = 0; i < gltf.scene.children[0].children.length; i += 1) {
    const item = gltf.scene.children[0].children[i];
    // 控制器分组
    const folder = gui.addFolder(item.name);
    
    // 定位变化操作
    const posFolder = folder.addFolder('定位')
    posFolder.add(Object.assign({}, pos), 'x').name('X').onChange((x) => handlePosChange(item, 'x', x));
    posFolder.add(Object.assign({}, pos), 'y').name('Y').onChange((y) => handlePosChange(item, 'y', y));
    posFolder.add(Object.assign({}, pos), 'z').name('Z').onChange((z) => handlePosChange(item, 'z', z));

    // 材质变化
    if (item.material) {
      const mtlFolder = folder.addFolder('材质');
      const colorData = Object.assign({}, color);
      mtlFolder.addColor(colorData, 'color').onChange((c) => handleColorChange(item, c))
    }

    // 默认折叠
    folder.close();
  }
});

// 控制器
const controller = new OrbitControls(camera, renderer.domElement);
controller.addEventListener('change', render);
controller.target.set(0, 2, 0);
controller.update();

// 自适应
const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);

  render();
};
window.addEventListener('resize', handleWindowResize);

// 初次渲染
render();
